package danran.dbapi.controller;

import danran.dbapi.common.ResponseDto;
import danran.dbapi.controller.util.JwtUtil;
import danran.dbapi.domain.User;
import danran.dbapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Classname UserController
 * @Description TODO
 * @Date 2022/1/17 12:44
 * @Created by RanCoder
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public ResponseDto login(String username, String password) {
        User user = userService.getUser(username, password);
        if (user == null) {
            return ResponseDto.fail("用户名或密码错误！");
        }
        String token = JwtUtil.createToken(user.getId().toString(), user.getPassword());
        return ResponseDto.successWithMsg(token);
    }

    @RequestMapping("/resetPassword")
    public ResponseDto resetPassword(String username, String password) {
        try {
            userService.resetPassword(username, password);
        } catch (Exception e) {
            return ResponseDto.fail("服务端出错，请稍后再试");
        }
        return ResponseDto.successWithMsg("密码重置成功");
    }

    @RequestMapping("/register")
    public ResponseDto register(String username, String password) {
        userService.insertUser(new User(username, password));
        return ResponseDto.successWithMsg("注册成功");
    }
}
